package com.sinostride.hibernate.controller;

/**
 * get()和load()区别
      相同点：按照主键ID做条件查询某个对象
      不同点如下：
       --load采用了延迟加载机制,get为立刻加载。
       --load如果没有符合记录，会抛出ObjectNotFoundException; 而get方法返回的是null,不会出现异常。
         
         session.load(Cost.class,11235)如果id不存在，则抛出异常
         session.get(Cost.class,11235)为null

       --load返回的是一个动态生成一个类型，get方法返回的是实体类型。
 */
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.sinostride.hibernate.model.User;
//@Scope("prototype")
@Controller
@RequestMapping("/user")
@SuppressWarnings("unchecked")
public class UserControll {
	//1、读取配置文件
	@Resource(name="sessionFactory")
	private SessionFactory sessionFactory;	//2、创建sessionFactory
	
	private Session session;
	private Transaction transaction;
	
	//打开
	public void openSession(){
		session = sessionFactory.openSession();
		transaction = session.beginTransaction();
	}
	
	//关闭
	public void close(){
		if (session != null && session.isOpen()) {
			session.close();//session.clear(),close()=clear()+close()。
			sessionFactory.close(); 
		}
		
	}
	
	//登录
	@RequestMapping("/login")
	public ModelAndView login(String name ,String password){
		ModelMap modelMap = new ModelMap();
		User user = new User();
		
		openSession();
		List<User> list = session.createQuery("from User").getResultList();
		
		modelMap.addAttribute("list", list);
		
		Iterator it = list.iterator();
		while(it.hasNext()){
			user = (User) it.next();
			System.out.println(user);
			if(user.getName().equals(name) && user.getPassword().equals(password)){
				System.out.println("登录信息匹配");
//				close();
				return new ModelAndView("testPage",modelMap);
				
			}
		}
		return new ModelAndView("error");
	}
	
	//查询所有人
	/*public List<User> selectUser(){
		List<User> list = session.createQuery("from User").getResultList();
		return list;
	}
	// 人数/(除以)要分的人数
	public int getTotalPages(int count , int pageSize){
		int totalPages = 0;
		totalPages = (count%pageSize==0)?(count/pageSize):(count/pageSize+1);
		return totalPages;
	}
	public int getCount(){
		String hql = "select count(*) from User";
		Query q = session.createQuery(hql);
		List list =q.getResultList();
		String li = list.get(0).toString();
		Integer count = Integer.parseInt(li);
		return count;
	}
	public List<User> seUser(int pageIndex ,int pageSize){
		Query query = session.createQuery("from User");
		query.setFirstResult((pageIndex-1)*pageSize);
		query.setMaxResults(pageSize);
		List<User> result = query.getResultList();
		return result;
	}*/
	
	
	//注册
	@RequestMapping("/register")
	public String registerIntoUser(){
		return "register";
	}
	
	@RequestMapping("saveRegister")
	public void saveRegister(String name, String password, Integer age, Timestamp date,
			HttpServletRequest request, HttpServletResponse response) throws IOException{
		System.out.println("into");
		User user = new User();
		user.setName(name);
		user.setPassword(password);
		user.setAge(age);
		user.setDate(date);
		
		openSession();
		session.save(user);
		
//		session.flush();//同步到数据库
//	    session.clear();//清空缓存，若不及时清理缓存，将会发生内存溢出异常。
	    
		transaction.commit(); //commit()=session.flush()+commit()
//		transaction.rollback();//回滚事务
		System.out.println("注册成功");
//		close();
		
		response.sendRedirect(request.getContextPath()+"/index.jsp");
	}
	
	@RequestMapping("deleteUser")
	public ModelAndView delete(int id){
		openSession();
		
//		User deleteUser =(User) session.createQuery("from User where id="+id).uniqueResult(); //方法1
		
		// 先加载一个持久化对象
		User deleteUser = session.get(User.class, new Integer(id));							  //方法2
		System.out.println(deleteUser.toString());
		session.delete(deleteUser);
		
		
		System.out.println("deleteId is "+id);
		transaction.commit();  //提交事务，清理缓存

		List<User> list =session.createQuery("from User").getResultList();
		ModelMap modelMap = new ModelMap();
		modelMap.addAttribute("list", list);
//		close();
		return new ModelAndView("testPage",modelMap);
	}
	
	@RequestMapping("upUser")
	public ModelAndView update(int id ){
		ModelMap modelMap = new ModelMap();
		openSession();
		List<User> upUser = session.createQuery("from User where id="+id).getResultList();
//		user = session.get(User.class, new Integer(id));
		
		/* 已过时
		 * String hql = "from User where id = ?";
		 *Query query = session.createQuery(hql);
		 *query.setInteger(0, id);
		 *List<User> upUser = query.getResultList();
		*/
		for(User user : upUser){
			System.out.println(user.getName()+":"+user.getId());
		
			modelMap.addAttribute("upUser", user);
			return new ModelAndView("update",modelMap);
		}
		return null;
	}
	
	@RequestMapping("updateUser")
	public ModelAndView updateUser(int id, String name, int age, String password){
		openSession();
		User user = new User();
		
		user = session.get(User.class, new Integer(id));
		user.setName(name);
		user.setAge(age);
		user.setPassword(password);
		System.out.println("----"+user.toString());
		
		session.update(user);
		transaction.commit();
		
		List<User> list =session.createQuery("from User").getResultList();
		System.out.println(list.toString());
		ModelMap modelMap = new ModelMap();
		modelMap.addAttribute("list", list);
//		close();
		return new ModelAndView("testPage",modelMap);
	}
}
